const express = require("express");
const router = express.Router();

const db = require("../utils/db");

// 注册接口
router.post("/api/reg", (req, res) => {
  // 1 获取前端传递过来的参数
  let { username, password } = req.body;
  // 2 验证参数是否合法
  // 3 验证用户名是否已经注册
  let sql = `select * from users where username='${username}'`;
  db.query(sql, (err, result) => {
    if (err) {
      res.json({
        status: 500,
        msg: "服务器内部错误",
      });
    } else {
      if (result.length > 0) {
        // 用户名已经注册
        res.json({
          status: 200,
          msg: "用户名已经注册",
        });
      } else {
        // 默认role为'reader
        let sql = `insert into users (username, password) values ('${username}', '${password}')`;
        db.query(sql, (err, result) => {
          if (err) {
            res.json({
              status: 500,
              msg: "服务器内部错误",
            });
          } else {
            res.json({
              code: 200,
              msg: "注册成功",
            });
          }
        });
      }
    }
  });
});

module.exports = router;
